package bloothdemo.bloothdemo;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 0;
    private BluetoothAdapter bluetoothAdapter;
    @ViewById
    ListView lv;

    private MyDeviceAdapter myDeviceAdapter;
    private MyBluetoothReceive receiver;
    private List<BluetoothDevice> list;
    private OutputStream outputStream;


    @AfterViews
    void initView() {
        requestPermission();
        initBluetooth();
        registerReceiver();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }
    }

    private void initBluetooth() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        receiver = new MyBluetoothReceive();
        registerReceiver(receiver, filter); // Don't forget to unregister during onDestroy
    }

    @Click(R.id.open_bluetooth)
    void openBluetooth() {
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙设备", Toast.LENGTH_SHORT).show();
        } else if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 0);
        } else {
            Toast.makeText(this, "蓝牙已经打开", Toast.LENGTH_SHORT).show();
        }
    }

    @Click(R.id.close_bluetooth)
    void closeBluetooth() {
        if (bluetoothAdapter.isEnabled()) {
            //关闭蓝牙
            bluetoothAdapter.disable();
        } else {
            Toast.makeText(this, "蓝牙已经关闭", Toast.LENGTH_SHORT).show();

        }
    }

    @Click(R.id.scan_bluetooth)
    void scanBluetooth() {
        if (bluetoothAdapter.isEnabled()) {
            if (!bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.startDiscovery();
            } else {
                Toast.makeText(this, "正在扫描", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "蓝牙还没打开", Toast.LENGTH_SHORT).show();
        }
    }

    @Click(R.id.turn_on_light)
    void turnOnLight() {
        controlLight(0);
    }

    private void controlLight(int type) {
        if (outputStream == null) {
            Toast.makeText(this, "还没有连接蓝牙设备", Toast.LENGTH_SHORT).show();
        }
        try {
            byte[] b = new byte[5];
            b[0] = (byte) 0x01;
            b[0] = (byte) 0x99;
            switch (type) {
                case 0:
                    b[0] = (byte) 0x10;
                    b[0] = (byte) 0x10;
                    break;
                case 1:
                    b[0] = (byte) 0x11;
                    b[0] = (byte) 0x11;
                    break;
                case 2:
                    b[0] = (byte) 0x12;
                    b[0] = (byte) 0x12;
                    break;
                case 3:
                    b[0] = (byte) 0x13;
                    b[0] = (byte) 0x13;
                    break;
                default:
                    break;
            }
            b[0] = (byte) 0x99;
            outputStream.write(b);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Click(R.id.turn_off_light)
    void turnOffLight() {
        controlLight(1);
    }

    @Click(R.id.stop_scan)
    void stopScan() {
        if (bluetoothAdapter.isEnabled()) {
            if (!bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();
            } else {
                Toast.makeText(this, "蓝牙已经停止扫描", Toast.LENGTH_SHORT).show();
            }

        }
    }


    class MyBluetoothReceive extends BroadcastReceiver implements AdapterView.OnItemClickListener {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                    Toast.makeText(context, "蓝牙开始扫描", Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    Toast.makeText(context, "蓝牙停止扫描", Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothDevice.ACTION_FOUND:
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    BluetoothDevice device = intent
                            .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (!list.contains(device)) {
                        list.add(device);
                    }
                    if (lv.getAdapter() == null) {
                        myDeviceAdapter = new MyDeviceAdapter(context, list);
                        lv.setAdapter(myDeviceAdapter);
                        lv.setOnItemClickListener(this);
                    } else {
                        myDeviceAdapter.setList(list);
                        myDeviceAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            BluetoothDevice device = list.get(i);
            connnectBlueDevice(device);
        }
    }

    private void connnectBlueDevice(final BluetoothDevice device) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                bluetoothAdapter.cancelDiscovery();
                BluetoothSocket bluetoothSocket = null;
                try {
                    bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                    outputStream = bluetoothSocket.getOutputStream();
                    bluetoothSocket.connect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Looper.prepare();
                Toast.makeText(MainActivity.this, "链接成功", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }).start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // TODO request success
                }
                break;
        }
    }


}
